package com.pluszg.nutrition.account.service.impl;

import com.pluszg.nutrition.account.service.AccountService;
import com.pluszg.nutrition.database.mapper.account.AccountMapper;
import com.pluszg.nutrition.model.account.Account;
import com.pluszg.nutrition.common.exception.PlusBusinessException;
import com.pluszg.nutrition.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public Account add (Account account){
        log.info("账户添加方法");
        account.setId(RandomUtil.generateUUID());
        accountMapper.insert(account);
        return account;
    }

    @Override
    public Account findById (String id){
        log.info("账户查询方法");
        return accountMapper.loadById(id).orElseThrow(()-> new PlusBusinessException("未找到对应账户"));
    }

    @Transactional
    @Override
    public Account modify (Account account){
        log.info("账户修改方法");
        accountMapper.update(account);
        return account;
    }

    @Override
    public Boolean delete (String id){
        log.info("账户删除方法");
        accountMapper.deleteById(id);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = PlusBusinessException.class)
    @Override
    public void reduceAccount(String id, BigDecimal amount) {
        Account account = this.findById(id);
        if (ObjectUtils.isEmpty(account)) {
            throw new PlusBusinessException("未找到账户");
        }
        BigDecimal subAmount = account.getAmount().subtract(amount);
        if (subAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new PlusBusinessException("账户余额不足");
        }
        account.setAmount(subAmount);
        accountMapper.update(account);
    }

}
